//
//  CharTableViewController.m
//  6.10.QQ
//
//  Created by lovena on 15/6/11.
//
//

#import "CharTableViewController.h"
#import "XQMessage.h"
#import "XQMessageSet.h"
#import "CharTableViewCell.h"
@interface CharTableViewController ()<UIAlertViewDelegate>
//数组
@property(nonatomic,retain)NSMutableArray *messageArray;
@property(nonatomic,strong)UIView *bgView;
@end

@implementation CharTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //分栏控制器隐藏芬兰
   // self.tabBarController.tabBar.hidden=YES;
    //表的背景色
    _tableView.backgroundColor=[UIColor colorWithRed:0.9 green:0.9 blue:0.9 alpha:1.0];
    //键盘监听
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyChange:) name:UIKeyboardWillChangeFrameNotification object:nil];
    //文本框左边间距
    _textField.leftView=[[UIView alloc]initWithFrame:CGRectMake(5, 0, 0, 0)];
    self.textField.leftViewMode=UITextFieldViewModeAlways;
}
//把监听消除
-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
//导入plist
-(NSArray *)messageArray
{
    if(_messageArray ==nil)
    {
        NSString *path=[[NSBundle mainBundle]pathForResource:@"messages.plist" ofType:nil];
        NSArray *array=[NSArray arrayWithContentsOfFile:path];
        NSMutableArray *array2=[NSMutableArray array];
        for (NSDictionary *dic in array) {
            XQMessage *mess=[[XQMessage alloc]initWithMessage:dic];
            //比较两个对话框的时间
            XQMessageSet *mset=[array2 lastObject];
            XQMessage *mess2=mset.message;
            mess.timeHidden=([mess.time isEqualToString:mess2.time]);
            //存数据
            XQMessageSet *mset2=[[XQMessageSet alloc]init];
            mset2.message=mess;
            [array2 addObject:mset2];
        }
        _messageArray=array2;
    }
    return _messageArray;
  }
//三步
//段
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
//行
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.messageArray.count;
}
//单元格内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CharTableViewCell *cell=[CharTableViewCell initWithChar:tableView];
    cell.messageset=self.messageArray[indexPath.row];
    return cell;
}

//行高
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [self.messageArray[indexPath.row] cellheight];
}

//键盘监听事件
-(void)keyChange:(NSNotification*)note
{
    // 1.设置窗口颜色
    self.view.window.backgroundColor = self.tableView.backgroundColor;
    
    // 2.取得键盘参数
    CGFloat duration = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    CGFloat keyboardY = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue].origin.y;
    
    // 3.动画
    [UIView animateWithDuration:duration animations:^{
        CGFloat ty = keyboardY - self.view.frame.size.height;
        self.view.transform = CGAffineTransformMakeTranslation(0, ty);
    }];

}
//代理
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    //自己发消息
    
    [self addText:textField.text type:MessageMe];
    //别人回复
    [self addText:[NSString stringWithFormat:@"悄悄告诉你，其实我不会告诉你任何答案，因为我是人工智能，不是人工服务，你看我的回复时间，其实我是在隔着时空和你聊天。不要问我这有什么区别，人工的世界，你不懂！！！"] type:MessageOther];
    //清除
    self.textField.text=nil;
    
    return NO;
}
//输入事件
-(void)addText:(NSString *)text type:(MessagePerson)type
{
    //时间格式化
    NSDateFormatter *fmt=[[NSDateFormatter alloc]init];
    fmt.dateFormat=@"HH:mm";
    //创建消息
    XQMessage *mess=[[XQMessage alloc]init];
    mess.text=text;
    mess.time=[fmt stringFromDate:[NSDate date]];
    mess.type=type;
    
    //与上一条消息时间比较
    XQMessageSet *mset=[self.messageArray lastObject];
    XQMessage *mess2=mset.message;
    mess2.timeHidden=([mess.time isEqualToString:mess2.time]);
    
    //添加消息
    XQMessageSet *mset2=[[XQMessageSet alloc]init];
    mset2.message=mess;
    [self.messageArray addObject:mset2];
    
    //刷新表格
    [self.tableView reloadData];
    //滑动到最后一行
    NSIndexPath *index=[NSIndexPath indexPathForRow:self.messageArray.count-1 inSection:0];
    
    [self.tableView scrollToRowAtIndexPath:index atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    
}

//键盘推出
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self.view endEditing:YES];
}

- (IBAction)returnXQ {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (IBAction)rightBtn {
    UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"我要愤怒了" message:@"俺已经明确告诉你俺是人工智能了，你还要评价，送你两个字：回你的火星去吧！！！" delegate:self cancelButtonTitle:@"就不回" otherButtonTitles:@"好吧，我回去", nil];
    [alert show];
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:3];
    if (buttonIndex==0) {

        _bgView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 480)];
        _bgView.backgroundColor=[UIColor blackColor];
        [self.view addSubview:_bgView];
        UILabel *label=[[UILabel alloc]initWithFrame:CGRectMake(0, 200, 320, 80)];
        label.backgroundColor=[UIColor clearColor];
        label.textColor=[UIColor whiteColor];
        label.text=@"不回我就黑屏，除非你关机重启。。。";
        label.textAlignment=NSTextAlignmentCenter;
        label.font=[UIFont systemFontOfSize:18];
        [_bgView addSubview:label];
        [self performSelector:@selector(hiddenView) withObject:nil afterDelay:5];
    }

    [UIView commitAnimations];
}
-(void)hiddenView
{
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:3];
    [_bgView removeFromSuperview];
    _bgView=nil;
    [UIView commitAnimations];
}
@end
